package com.wu.dms.dao.sqlProvide;

import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Cousin
 * @date 2025/1/6
 * @Description
 */
public class CommentSqlProvider {
    public String getCommentInPage(Integer resourceType,
                                   String searchWord, Integer pageNum, Integer pageSize,
                                   String startDate, String endDate) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT comment.id as id, user.id as userId, user.name as username, ");
        sql.append("comment.content as content, comment.create_time as createTime, comment.up, ");
        sql.append("resource.name as resourceName, resource.type as resourceType , resource.id as resourceId ");

        pageQuerySame(resourceType, searchWord, startDate, endDate, sql);

        sql.append("ORDER BY comment.up DESC ");

        // 添加分页逻辑
        int offset = (pageNum - 1) * pageSize;
        sql.append("LIMIT ").append(offset).append(", ").append(pageSize);

        return sql.toString();
    }

    public String countCommentInPage(Integer resourceType,
                                     String searchWord,
                                     String startDate, String endDate) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT COUNT(*) ");

        pageQuerySame(resourceType, searchWord, startDate, endDate, sql);

        return sql.toString();
    }

    private void pageQuerySame(Integer resourceType, String searchWord,
                               String startDate, String endDate, StringBuilder sql) {
        sql.append("FROM music.comment ");
        sql.append("JOIN music.user ON user.id = comment.user_id ");
        sql.append("JOIN music.resource ON resource.id = comment.resource_id ");
        sql.append("WHERE (resource.name LIKE CONCAT('%', #{searchWord}, '%') ");
        sql.append("OR user.name LIKE CONCAT('%', #{searchWord}, '%')) ");
        if (ObjectUtil.isNotNull(resourceType)) {
            sql.append("AND resource.type = #{resourceType} ");
        }
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append("AND comment.create_time >= #{startDate} ");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append("AND comment.create_time <= #{endDate} ");
        }
        sql.append("AND comment.status = 0 ");
        sql.append("AND resource.status = 0 ");
    }
}